define(function() {
    
    return {
        go: function() {
            $loading();
            var query = JSON.stringify({"threads": "SELECT thread_id, subject, snippet, snippet_author, object_id, unread, viewer_id, message_count, updated_time, subject, recipients FROM thread WHERE folder_id = 0", "users": "SELECT uid, name FROM user WHERE uid IN(SELECT recipients FROM thread WHERE folder_id = 0)"});
            FB.api('fql', {q: query}, $.proxy(this.template, this));
        },
        format: function(set) {
            var set = set.data;
            var users = set[1].fql_result_set,
                threads = set[0].fql_result_set,
                getName = function(uid) {
                    var name = 'Unkown';
                    $.each(users, function() {
                        if(this.uid == uid) {
                            name = this.name;
                            return false;
                        }
                    });
                    
                    return name;
                };
            $.each(threads, function() {
                this.snippet = this.snippet.replace(/\n/g, '<br />');
                
                this.id = this.thread_id;
                if(this.recipients[0] != FB.getUserID()) {
                    this.from = {id: this.recipients[0], name: getName(this.recipients[0])};
                } else {
                    this.from = {id: this.recipients[1], name: getName(this.recipients[1])};
                }
                this.ago = moment(new Date(this.updated_time * 1000)).fromNow();
                window.cache[this.id] = this;
            });
            return threads;
        },
        formatOld: function(threads) {
            $.each(threads, function() {
                this.snippet = this.snippet.replace(/\n/g, '<br />');
                
                if(this.participants.data[0].id != FB.getUserID()) {
                    this.from = {id: this.participants.data[0].id, name: this.participants.data[0].name};
                } else {
                    this.from = {id: this.participants.data[1].id, name: this.participants.data[1].name};
                }
                this.ago = moment(new Date(this.updated_time)).fromNow();
                window.cache[this.id] = this;
            });
            return threads;
        },
        template: function(res) {
            Template('inbox', {threads: this.format(res)}, function(html) {
                $content.html(html);
            });
        }
    }
});